//
//  MainViewController.swift
//  cysLibrarySys
//
//  Created by 曹亚索 on 2021/6/24.
//

import UIKit
import LeanCloud

var currentBook : Book?{
    didSet{
        if let image = currentBook?.face, let imageView = detailViewController.bookFaceImageView{
            imageView.image = image
        }
    }
}
var searchBooks : [Book] = []

private let tableCellReuseIdentifier = "BookTableCell"
private let collectionCellReuseIdentifier = "BookCollectionCell"
private let detailViewController = DetailViewController()

@available(iOS 13.0, *)
class MainViewController: UIViewController {
    
    private var itemHeight : CGFloat = 80
    private let itemSize : CGSize = CGSize(width: 300, height: 180)
    private var currentIndex : IndexPath!
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var collectionView: UICollectionView!
    @IBOutlet weak var personAvatar: UIBarButtonItem!
    @IBOutlet weak var scrollView: UIScrollView!
    @IBOutlet weak var searchBar: UISearchBar!
    @IBOutlet weak var containView: UIView!
    private var detailView : DetailView!
    private var isBack: Bool = false
    private let hiddenOrigin: CGPoint = {
        let y = UIScreen.main.bounds.height - (UIScreen.main.bounds.width * 9 / 32) - 10
        let x = -UIScreen.main.bounds.width
        let coordinate = CGPoint.init(x: x, y: y)
        return coordinate
    }()
    private var isSearchMode : Bool = false{
        didSet{
            self.tableView.reloadData()
        }
    }
    
    private var bookCommanded : [Book]{
        var books : [Book] = []
        if localLibrary.allBook.isEmpty == false{
            for i in 0...4{
                let book = localLibrary.allBook[i]
                books.append(book)
            }
        }
        return books
    }
    
    private var localLibraryIsFinishInit: Bool = false{
        didSet{
            //页面重载
            collectionView.reloadData()
            tableView.reloadData()
            //隐藏searchBar
            UIView.animate(withDuration: 0.5) {
                self.tableView.contentOffset = CGPoint(x: 0, y: self.searchBar.frame.height)
            }
        }
    }
    
    //MARK:LifeCycle
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setUpDetailView()
        scrollViewCommonInit()
        tableViewCommonInit()
        collectionViewCommonInit()
        searchBarCommonInit()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        if localLibraryIsFinishInit == false{
            LC.getLCLibrary {
                //本地书库完成加载
                self.localLibraryIsFinishInit = true
                //获取用户信息
                self.setUpUserData()
            }
        }
    }
    
    @IBAction func showSearchBar(_ sender: Any) {
        UIView.animate(withDuration: 0.3) {
            self.tableView.contentOffset = .zero
            self.searchBar.becomeFirstResponder()
        }
    }
    //MARK:SetUpUser
    private func setUpUserData(){
        if let user = LCApplication.default.currentUser{
            let avatar = user.get("avatar")?.stringValue
            let username = user.get("username")?.stringValue
            userSelf = User(username: username!, avatar: avatar)
            LC.getUserBookData()
        }
    }
    
    //setUpDetailView
    private func setUpDetailView(){
        let nib = UINib(nibName: "DetailView", bundle: nil)
        let loadObject = nib.instantiate(withOwner: self, options: nil)
        if let detailView = loadObject[0] as? UIView{
            let hiddenPoint = CGPoint(x: 0, y: UIScreen.main.bounds.height)
            self.detailView = detailView as? DetailView
            self.detailView.layer.cornerRadius = self.detailView.frame.width / 10
            self.detailView.layer.shadowOpacity = 1
            self.detailView.layer.shadowOffset = CGSize(width: 10, height: 10)
            self.detailView.layer.shadowColor = UIColor.gray.cgColor
            self.detailView.frame = CGRect(origin: hiddenPoint, size: CGSize(width: UIScreen.main.bounds.width * 0.8, height: UIScreen.main.bounds.height * 0.6))
            self.detailView.bookFaceImageView.isUserInteractionEnabled = true
            self.detailView.bookFaceImageView.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: #selector(panGesture(sender:))))
            self.view.addSubview(self.detailView)
        }
        
    }
    
    @objc func panGesture(sender:UIPanGestureRecognizer){
        let factor = 1 - abs(sender.translation(in: nil).y/UIScreen.main.bounds.height)
        let scale = CGAffineTransform(scaleX: factor, y: factor)
        let transfrom = scale.concatenating(CGAffineTransform(translationX: sender.translation(in: nil).x, y: sender.translation(in: nil).y))
        detailView.transform = transfrom
        detailView.alpha = factor
        if sender.state == .ended{
            if sender.translation(in: nil).y > UIScreen.main.bounds.height / 100{
                dismissAnimate()
            }else{
                UIView.animate(withDuration: 0.2) { [self] in
                    detailView.transform = .identity
                    detailView.alpha = 1
                }
            }
        }
    }
    
    private func dismissAnimate(){
        let animateTime = 0.4
        UIView.animate(withDuration: animateTime) {
            self.detailView.transform = CGAffineTransform(scaleX: 0.2, y: 0.2)
            Timer.scheduledTimer(withTimeInterval: animateTime, repeats: false) { [self] (timer) in
                detailView.transform = .identity
                detailView.alpha = 1
                detailView.frame.origin = hiddenOrigin
                timer.invalidate()
            }
        }
    }
    
    private func scrollViewCommonInit(){
        if let scrollView = self.scrollView{
            scrollView.contentSize = CGSize(width: view.frame.width, height: collectionView.frame.height * 2 + tableView.frame.height)
        }
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "shareBook"{
            let vc = segue.destination as! ShareViewController
            vc.navigationItem.title = "分享"
        }
    }
    
}

//MARK:CollectionView
@available(iOS 13.0, *)
extension MainViewController: UICollectionViewDataSource, UICollectionViewDelegate{
    func collectionViewCommonInit(){
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        collectionView.topAnchor.constraint(equalTo: searchBar.bottomAnchor).isActive = true
        collectionView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        collectionView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
        collectionView.bottomAnchor.constraint(equalTo: tableView.tableHeaderView!.bottomAnchor).isActive = true
        collectionView.collectionViewLayout = BookcollectionViewLayout(itemSize: CGSize(width: collectionView.frame.width * 0.7, height: collectionView.frame.height * 0.7))
        //注册nib文件
        let nib = UINib(nibName: collectionCellReuseIdentifier, bundle: nil)
        collectionView.register(nib, forCellWithReuseIdentifier: String(describing: BookCollectionCell.self))
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return bookCommanded.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: BookCollectionCell.self), for: indexPath) as! BookCollectionCell
        cell.layer.cornerRadius = 20
        if let image = bookCommanded[indexPath.item].face{
            cell.bookFace.image = image
        }else{
            cell.bookFace.image = #imageLiteral(resourceName: "Password-hide")
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        currentBook = bookCommanded[indexPath.row]
        presentDetailView()
    }
    
    private func presentDetailView(){
        detailView.bookFaceImageView.image = currentBook?.face
        detailView.abstractLabel.text = currentBook?.abstract
        detailView.abstractLabel.sizeToFit()
        UIView.animate(withDuration: 0.3) {[self] in
            let openPoint = CGPoint(x: self.view.center.x - detailView.frame.width / 2, y: self.view.center.y - detailView.frame.height / 2)
            detailView.frame.origin = openPoint
        }
    }
    
}
//MARK:TableView
@available(iOS 13.0, *)
extension MainViewController: UITableViewDataSource, UITableViewDelegate{
    
    func tableViewCommonInit(){
        tableView.tableHeaderView?.frame = CGRect(origin: .zero, size: CGSize(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height * 0.3))
        self.tableView.dataSource = self
        self.tableView.delegate = self
        self.tableView.rowHeight = itemHeight
        //注册nib文件
        let nib = UINib(nibName: tableCellReuseIdentifier, bundle: nil)
        self.tableView.register(nib, forCellReuseIdentifier: String(describing: BookTableCell.self))
        self.tableView.contentOffset = CGPoint(x: 0, y: searchBar.frame.height)
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 25
    }
    
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return "↓下拉搜索↓"
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        var bookNum : Int
        switch isSearchMode {
        case true:
            bookNum = searchBooks.count
        case false:
            bookNum = localLibrary.allBook.count
        }
        return bookNum
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: tableCellReuseIdentifier, for: indexPath) as! BookTableCell
        var bookDataSource: [Book]
        switch isSearchMode {
        case true:
            bookDataSource = searchBooks
        case false:
            bookDataSource = localLibrary.allBook
        }
        if let image = bookDataSource[indexPath.item].face{
            cell.bookFace.image = image
        }else{
            cell.bookFace.image = #imageLiteral(resourceName: "Password-hide")
        }
        if let bookName = bookDataSource[indexPath.item].name{
            cell.bookNameLabel.text = bookName
        }else{
            cell.bookNameLabel.text = "?"
        }
        if let author = bookDataSource[indexPath.item].author{
            cell.authorLabel.text = author
        }else{
            cell.authorLabel.text = "?"
        }
        if let abstract = bookDataSource[indexPath.item].abstract{
            cell.abstractLabel.text = abstract
        }else{
            cell.abstractLabel.text = "?"
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        switch isSearchMode {
        case true:
            currentBook = searchBooks[indexPath.row]
        case false:
            currentBook = localLibrary.allBook[indexPath.row]
        }
        currentIndex = indexPath
        searchBar.resignFirstResponder()
        detailViewController.reSetDelegate = self
        detailViewController.cancelSelectedDelegate = self
        present(detailViewController, animated: true, completion: nil)
    }
    
}
//MARK:CancelSelectedDelegate
@available(iOS 13.0, *)
extension MainViewController: CancelSelectedDelegate{
    func cancelSelected() {
        isBack = true
        UIView.animate(withDuration: 0.2) { [self] in
            tableView.cellForRow(at: currentIndex)?.isSelected = false
        }
    }
}
//MARK:SearchBar
@available(iOS 13.0, *)
extension MainViewController: UISearchBarDelegate{
    
    private func searchBarCommonInit(){
        searchBar.placeholder = "请输入书名"
    }
    
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        if let string = searchBar.text{
            searchBooks.removeAll()
            LC.searchBook(match: string) {
                self.isSearchMode = true
            }
        }
    }
    
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        if searchText.isEmpty == true{
            isSearchMode = false
        }
    }
    //收起搜索框
    func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
        UIView.animate(withDuration: 0.5) {
            self.tableView.contentOffset = CGPoint(x: 0, y: searchBar.frame.height)
        }
    }
    
}
//MARK:ResetDelegate
@available(iOS 13.0, *)
extension MainViewController: ReSetDelegate{
    
    func reSet(ConnectedBook: Book) {
        detailViewController.reSetDelegate = self
        currentBook = ConnectedBook
        navigationController?.pushViewController(detailViewController, animated: true)
    }
    
}
